/**
 * 
 */
package com.netflexitysolutions.amazonws.sdb.internal.operations;

import java.util.ArrayList;
import java.util.List;

import javax.xml.ws.soap.SOAPFaultException;

import com.amazonaws.sdb.doc._2009_04_15.ListDomains;
import com.amazonaws.sdb.doc._2009_04_15.ListDomainsResponse;
import com.amazonaws.sdb.doc._2009_04_15.ListDomainsResult;
import com.amazonaws.sdb.doc._2009_04_15.ResponseMetadata;
import com.netflexitysolutions.amazonws.sdb.Domain;
import com.netflexitysolutions.amazonws.sdb.SimpleDB;
import com.netflexitysolutions.amazonws.sdb.Statistics;

/**
 * @author netflexity
 *
 */
public class ListDomainsOperation extends OperationExecutor<ListDomains, List<Domain>>{

	// 100 is the maximum allowed domains.
	private int maxNumberOfDomains = 100;
	
	/**
	 * @param simpleDB
	 * @param maxNumberOfDomains
	 * @param nextToken
	 */
	public ListDomainsOperation(SimpleDB simpleDB, int maxNumberOfDomains, String nextToken) {
		super(simpleDB);
		this.maxNumberOfDomains = maxNumberOfDomains;
		setNextToken(nextToken);
	}
	
	/* (non-Javadoc)
	 * @see com.netflexitysolutions.amazonws.sdb.internal.OperationExecutor#call(java.lang.Object)
	 */
	@Override
	protected List<Domain> call(ListDomains request){
		List<Domain> domains = new ArrayList<Domain>();
		
		// Prepare request.
		request.setMaxNumberOfDomains(maxNumberOfDomains);
		request.setNextToken(nextToken);
		
		// Invoke operation.
		ListDomainsResponse response = null;
		try{
			response = getSimpleDB().getService().listDomains(request);
		}
		catch(SOAPFaultException fault){
			System.out.println("Got it:" + fault.getFault().getFaultString());
		}
		if(response != null){
			ResponseMetadata metadata = response.getResponseMetadata();
			if(metadata != null){
				this.stats = new Statistics(metadata.getRequestId(), metadata.getBoxUsage());
			}
			ListDomainsResult result = response.getListDomainsResult();
			if(result != null){
				this.nextToken = result.getNextToken();
				this.stats.setNextToken(this.nextToken);
				List<String> domainNames = result.getDomainName();
				for (String domainName : domainNames) {
					domains.add(new Domain(domainName));
				}
				this.stats.setRecordCount(domains.size());
			}
		}
		return domains;
	}

	/**
	 * @return the maxNumberOfDomains
	 */
	public int getMaxNumberOfDomains() {
		return maxNumberOfDomains;
	}

	/**
	 * @param maxNumberOfDomains the maxNumberOfDomains to set
	 */
	public void setMaxNumberOfDomains(int maxNumberOfDomains) {
		this.maxNumberOfDomains = maxNumberOfDomains;
	}
}
